package com.jn.algorithm.day015.question43;

/**
 * @author 江南大学1033190417
 * @date 2022/4/30 13:40
 */
public class Solution {

    public String multiply(String num1, String num2) {
        if ("0".equals(num1) || "0".equals(num2)) {
            return "0";
        }
        int l1 = num1.length();
        int l2 = num2.length();
        String ans = "0";
        for (int i = l2 - 1; i >= 0; i--) {
            StringBuilder cur = new StringBuilder();
            for (int j = 0; j < l2 - i - 1; j++) {
                cur.append(0);
            }
            int num = num2.charAt(i) - '0';
            int carry = 0;
            int l = l1 - 1;
            while (l >= 0 || carry != 0) {
                int temp = (l >= 0 ? num1.charAt(l) - '0' : 0) * num + carry;
                cur.append(temp % 10);
                carry = temp / 10;
                --l;
            }
            ans = addStrings(ans, cur.reverse().toString());
        }
        return ans;
    }

    public String addStrings(String num1, String num2) {
        int l1 = num1.length() - 1;
        int l2 = num2.length() - 1;
        int carry = 0;//进位
        StringBuilder ans = new StringBuilder();
        while (l1 >= 0 || l2 >= 0 || carry != 0) {
            int n1 = l1 >= 0 ? num1.charAt(l1) - '0' : 0;
            int n2 = l2 >= 0 ? num2.charAt(l2) - '0' : 0;
            int temp = n1 + n2 + carry;
            ans.append(temp % 10);
            carry = temp / 10;
            --l1;
            --l2;
        }
        return ans.reverse().toString();
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.multiply("9", "9"));
    }
}
